﻿using System;
using System.IO;
using System.Net;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace TireService.Data
{
    public class GoogleAPI
    {
    }


    public class LatLng 
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }

        public LatLng() { }

        public LatLng(double lat, double lng)
        {
            this.Latitude = lat;
            this.Longitude = lng;
        }
    }

    public class GoogleMaps 
    {
        private string API_KEY = string.Empty;

        public GoogleMaps(string api_key)
        {
            this.API_KEY = api_key;
        }

        public void SetApiKey(string key) 
        {
            if (key == null | key == "" | key == string.Empty) 
            {
                throw new ArgumentException("API Key is invalid");
            }

            this.API_KEY = key;
        }

        public LatLng GetLatLng(string addr) 
        {
            // Version 2.0 - Return CSV. OUTDATED: 9/9-2013
            //var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" + this.API_KEY + "&q=" + HttpContext.Current.Server.UrlEncode(addr);
            
            //var request = WebRequest.Create(url);
            //var response = (HttpWebResponse)request.GetResponse();

            //if (response.StatusCode == HttpStatusCode.OK) 
            //{
            //    var ms = new MemoryStream();
            //    var responseStream = response.GetResponseStream();

            //    var buffer = new Byte[2048];
            //    int count = responseStream.Read(buffer, 0, buffer.Length);

            //    while (count > 0) 
            //    {
            //        ms.Write(buffer, 0, count);
            //        count = responseStream.Read(buffer, 0, buffer.Length);
            //    }

            //    responseStream.Close();
            //    ms.Close();

            //    var responseBytes = ms.ToArray();
            //    var encoding = new System.Text.ASCIIEncoding();

            //    var coords = encoding.GetString(responseBytes);
            //    var parts = coords.Split(',');

            //    return new LatLng(Convert.ToDouble(parts[2]), Convert.ToDouble(parts[3]));
            //}

            //return null;

            // Version 3.0 - Return XML (or JSON) - DOC: https://developers.google.com/maps/documentation/geocoding/
            var url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + addr + "&sensor=false";
            try
            {
                XElement GoogFile = XElement.Load(url);
                var location = GoogFile.Descendants("location").First();
                var lat = location.Element("lat");
                var lng = location.Element("lng");

                return new LatLng(Convert.ToDouble(lat.Value), Convert.ToDouble(lng.Value));
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Helper function that returns longitude and latitude coordinates for a specific address from google maps 
        /// </summary>
        /// <param name="Address">Address to return coordinates for</param>
        /// <returns>Double array with longitude and latitude</returns>
        public double[] GetLongLatCoordinates(string Address)
        {
            double[] LongLatCoordinates = new double[2];

            LatLng latlng = GetLatLng(Address);
            LongLatCoordinates[0] = latlng.Longitude / 10000000;
            LongLatCoordinates[1] = latlng.Latitude / 10000000;

            return LongLatCoordinates;
        }
    }
}
